package com.senjoeson.abilityservice;

import android.os.Build;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.RequiresApi;

import com.senjoeson.abilityservice.service.AutoAccessibilityService;

import java.util.List;

/**
 * @USER senjoeson
 * @DATE 2021/1/31 10:17 下午
 * @Desc
 **/
public class ActionDelegateImpl implements ActionDelegate {


    private final AutoAccessibilityService autoAccessibilityService;

    public ActionDelegateImpl(AutoAccessibilityService autoAccessibilityService) {
        this.autoAccessibilityService = autoAccessibilityService;
    }

    @Override
    public boolean findText(String text) {
        AccessibilityNodeInfo rootInActiveWindow = autoAccessibilityService.getRootInActiveWindow();
        List<AccessibilityNodeInfo> openGallery = rootInActiveWindow.findAccessibilityNodeInfosByText("图库");
        if (openGallery != null && openGallery.size() > 0) {
            openGallery.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
            return true;
        }
        return false;
    }

    @Override
    public boolean findId(String id) {
        AccessibilityNodeInfo rootInActiveWindow = autoAccessibilityService.getRootInActiveWindow();
        List<AccessibilityNodeInfo> accessibilityNodeInfoByViewId = rootInActiveWindow.findAccessibilityNodeInfosByViewId(id);
        if (accessibilityNodeInfoByViewId != null && accessibilityNodeInfoByViewId.size() > 0) {
            return accessibilityNodeInfoByViewId.get(0).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public boolean swipeLeft() {
        AccessibilityNodeInfo rootInActiveWindow = autoAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo accessibilityNodeInfo = rootInActiveWindow.findAccessibilityNodeInfosByViewId("com.android.launcher3:id/workspace").get(0);
        return accessibilityNodeInfo.performAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SCROLL_LEFT.getId());
    }
}
